<script lang="ts" setup>
import type { PhaseType } from '@/types/micro-scene';
import SubTitle from './components/SubTitle.vue';
import { computed, onMounted, ref } from 'vue';
import { useUserStore } from '@/stores/useUserStore';
import { CheckOutlined, CloseOutlined, EditOutlined } from '@ant-design/icons-vue';
import { getPhaseInfo, updatePhaseTarget } from '@/api/MicroScene/MicroSceneDetailApi';
import { useRoute } from 'vue-router';
import { message } from 'ant-design-vue';
const props = defineProps<{
  phaseId: string
}>()
const route = useRoute()
const userStore = useUserStore()
const text = ref<string>('');
const getText = async () => {
  const response = await getPhaseInfo(route.params.id as string, props.phaseId)
  text.value = response.phaseTarget
}
onMounted(() => {
  getText();
})

const isEdit = ref(false);
const textCache = ref('');
const showEdit = computed(() => {
  return userStore.isEditMicroScene
})
const handleEdit = () => {
  isEdit.value = true;
  textCache.value = text.value;
}
const handleCancel = () => {
  isEdit.value = false;
  text.value = textCache.value;
}
const handleSave = async () => {
  isEdit.value = false;
  try {
    await updatePhaseTarget(Number(route.params.id), Number(props.phaseId), text.value)
  }
  catch (error) {
    await getPhaseInfo(route.params.id as string, props.phaseId)
    console.error('更新阶段目标失败', error)
    message.error('更新阶段目标失败')
  }
}
</script>

<template>
  <div class="flex flex-row">
    <SubTitle title="阶段目标" />
    <div class="flex gap-8 items-center ml-4">
      <!-- 标题编辑区域 -->
      <div v-if="showEdit">
        <a-button v-show="!isEdit" type="text" @click="handleEdit">
          <template #icon>
            <EditOutlined />
          </template>
        </a-button>
        <a-button v-show="isEdit" @click="handleCancel">
          <template #icon>
            <CloseOutlined />
          </template>
        </a-button>
        <a-button v-show="isEdit" type="primary" @click="handleSave">
          <template #icon>
            <CheckOutlined />
          </template>
        </a-button>
      </div>
    </div>
  </div>

  <div v-show="!isEdit" class="text-[0.875rem] my-4 leading-6 whitespace-pre-wrap">
    {{ text }}
  </div>
  <a-textarea v-show="isEdit" v-model:value="text" :auto-size="{ minRows: 3, maxRows: 10 }" class="w-full" />
</template>

<style lang="scss" scoped></style>
